import request from '../utils/api'
import { 
  mockDistributorTree, 
  mockStatistics, 
  mockDistributorDetail, 
  mockCommissionDetail, 
  wrapMockResponse, 
  delay 
} from '@/utils/mockDistributorData'

/**
 * 分销员管理 API
 * 当前使用模拟数据，后端接口开发完成后切换到真实API
 */

// 获取分销员树形结构
export const getDistributorTree = async (params = {}) => {
  try {
    // 尝试调用真实API
    return await request.get('/admin/distributor/tree', { params })
  } catch (error) {
    console.warn('分销员树形API未实现，使用模拟数据', error)
    await delay(300)
    // 根据门店筛选模拟数据
    let filteredData = mockDistributorTree
    if (params.store_id) {
      filteredData = mockDistributorTree.filter(item => item.store_id == params.store_id)
    }
    return wrapMockResponse(filteredData)
  }
}

// 获取分销员列表
export const getDistributorList = async (params = {}) => {
  try {
    return await request.get('/admin/distributor/list', { params })
  } catch (error) {
    console.warn('分销员列表API未实现，使用模拟数据', error)
    await delay(300)
    return wrapMockResponse([])
  }
}

// 获取分销员详情
export const getDistributorDetail = async (distributorId) => {
  // 参数验证
  if (!distributorId || distributorId === 'undefined' || distributorId === null) {
    throw new Error('分销员ID不能为空')
  }
  
  try {
    console.log('调用分销员详情API:', distributorId)
    return await request.get(`/admin/distributor/${distributorId}`)
  } catch (error) {
    console.warn('分销员详情API未实现，使用模拟数据', error)
    await delay(300)
    // 从树形数据中查找对应的分销员
    const findDistributor = (nodes, id) => {
      for (const node of nodes) {
        if (node.distributor_id == id) return node
        if (node.children && node.children.length > 0) {
          const found = findDistributor(node.children, id)
          if (found) return found
        }
      }
      return null
    }
    const distributor = findDistributor(mockDistributorTree, distributorId) || mockDistributorDetail
    return wrapMockResponse(distributor)
  }
}

// 获取分销员下级列表
export const getDistributorSubordinates = async (distributorId, params = {}) => {
  try {
    return await request.get(`/admin/distributor/${distributorId}/subordinates`, { params })
  } catch (error) {
    console.warn('分销员下级API未实现，使用模拟数据', error)
    await delay(300)
    return wrapMockResponse([])
  }
}

// 设置分销员
export const setDistributor = async (userId, data) => {
  try {
    return await request.post(`/admin/user/${userId}/set-distributor`, data)
  } catch (error) {
    console.warn('设置分销员API未实现，使用模拟数据', error)
    await delay(300)
    return wrapMockResponse({ success: true })
  }
}

// 停用/启用分销员
export const updateDistributorStatus = async (distributorId, status) => {
  // 参数验证
  if (!distributorId || distributorId === 'undefined' || distributorId === null) {
    throw new Error('分销员ID不能为空')
  }
  
  if (status !== 0 && status !== 1) {
    throw new Error('状态参数无效，只能是0或1')
  }
  
  try {
    console.log('调用更新分销员状态API:', distributorId, status)
    return await request.patch(`/admin/distributor/${distributorId}/status`, { status })
  } catch (error) {
    console.warn('更新分销员状态API未实现，使用模拟数据', error)
    await delay(300)
    return wrapMockResponse({ success: true })
  }
}

// 获取分销员佣金明细
export const getDistributorCommissionDetails = async (distributorId, params = {}) => {
  // 参数验证
  if (!distributorId || distributorId === 'undefined' || distributorId === null) {
    throw new Error('分销员ID不能为空')
  }
  
  try {
    console.log('调用分销员佣金明细API:', distributorId, params)
    return await request.get(`/admin/distributor/${distributorId}/commission-details`, { params })
  } catch (error) {
    console.warn('分销员佣金明细API未实现，使用模拟数据', error)
    await delay(300)
    return wrapMockResponse(mockCommissionDetail)
  }
}

// 获取分销员统计信息
export const getDistributorStatistics = async (params = {}) => {
  try {
    return await request.get('/admin/distributor/statistics', { params })
  } catch (error) {
    console.warn('分销员统计API未实现，使用模拟数据', error)
    await delay(300)
    return wrapMockResponse(mockStatistics)
  }
}

// 获取佣金配置
export const getCommissionConfig = (storeId = 0) => {
  return request.get('/admin/commission/config', { params: { store_id: storeId } })
}

// 更新佣金配置
export const updateCommissionConfig = (data) => {
  return request.post('/admin/commission/config', data)
}

// 获取佣金统计
export const getCommissionStatistics = (params = {}) => {
  return request.get('/admin/commission/statistics', { params })
}

// 获取提现申请列表
export const getWithdrawalApplications = (params = {}) => {
  return request.get('/admin/withdrawal/applications', { params })
}

// 处理提现申请
export const processWithdrawal = (withdrawalId, formData) => {
  return request.post(`/admin/withdrawal/${withdrawalId}/process`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取门店分销员列表
export const getStoreDistributors = async (storeId) => {
  // 参数验证
  if (!storeId || storeId === 'undefined' || storeId === null) {
    throw new Error('门店ID不能为空')
  }
  
  try {
    return await request.get(`/admin/distributor/store/${storeId}/list`)
  } catch (error) {
    console.warn('获取门店分销员API未实现，使用模拟数据', error)
    await delay(300)
    // 生成模拟数据
    const mockDistributors = [
      { distributorId: 1, userId: 201, nickname: '李一', distributorCode: 'D001001', level: 1, storeName: '门店' + storeId },
      { distributorId: 2, userId: 202, nickname: '王二', distributorCode: 'D001002', level: 1, storeName: '门店' + storeId },
      { distributorId: 3, userId: 203, nickname: '张三', distributorCode: 'D001003', level: 1, storeName: '门店' + storeId },
      { distributorId: 4, userId: 204, nickname: '赵四', distributorCode: 'D001004', level: 2, storeName: '门店' + storeId, parentId: 1 },
      { distributorId: 5, userId: 205, nickname: '刘五', distributorCode: 'D001005', level: 2, storeName: '门店' + storeId, parentId: 2 }
    ]
    return wrapMockResponse(mockDistributors)
  }
} 